package com.bookmarket.controller;

import com.bookmarket.entity.Admin;
import com.bookmarket.entity.Book;
import com.bookmarket.entity.Module;
import com.bookmarket.service.LQMainService;
import com.bookmarket.service.LQModuleService;
import com.bookmarket.utils.FileUtils;
import com.bookmarket.utils.TemplateUtils;
import com.github.pagehelper.Page;
import com.google.gson.Gson;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/useModule")
public class LQ_UseModuleController {

    @Resource
    private LQModuleService moduleService;

    /**
     * 查询所有模型返回JSON
     * @return
     */
    @RequestMapping("/module")
    public ModelAndView returnModule(){
        ModelAndView mv = new ModelAndView();
        Page page = moduleService.queryModule();
        mv.setViewName("backstage/LQ_index");
        mv.addObject("modules",page);
        return mv;
    }

    /**
     * Freemarker静态化
     */
    @RequestMapping(value="/createTemplate", method= RequestMethod.GET)
    public ModelAndView Add(int id,Configuration cfg,HttpServletRequest request) {
        Module module = moduleService.queryOneModule(id);//得到模块数据
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("module",module);
        map.put("bookList",moduleService.queryBook(module.getTypeId(),module.getModel()));//通过类型查数据
        map.put("imgList",moduleService.queryPicture(module.getModuleId()));//查询模块中的图片

        TemplateUtils.createStaticPage(request,String.valueOf(module.getModuleId()),map,module.getModel()+".ftl");

        return new ModelAndView("redirect:/before/template2/"+module.getModuleId()+".html");
    }

    /**
     * 保存首页JSON
     * @param modules 被选择的模块
     * @param request
     * @return
     */
    @RequestMapping(value="/indexJson")
    public ModelAndView indexJson(String[] modules,HttpServletRequest request) {
        Gson gson = new Gson();
        Map map = new HashMap();
        for(int i=0;i<modules.length;i++){
            map.put("id"+(i+1),modules[i]);
        }
        //Map转为JSON并进行保存
        FileUtils.createJSONFile(gson.toJson(map),request);
        return new ModelAndView("redirect:/test/module.do");
    }

    public void setModuleService(LQModuleService moduleService) {
        this.moduleService = moduleService;
    }

}
